package com.chenxi.vhr.controller;

import com.chenxi.vhr.bean.BaseUser;
import com.chenxi.vhr.bean.ws.WsChatMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;

import java.util.Date;

/**
 * WebSocket消息处理类
 * @author : zhangchenxi
 * @create : 2022-02-16
 **/
@Controller
public class WebSocketController {

    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    /**
     * 单聊
     * @param authentication   获取security登陆的用户
     * @param message          前端向服务端发送的的消息，服务端进行接收
     */
    @MessageMapping("/ws/chat")         // 服务端接收消息的接口
    public void chat(Authentication authentication, WsChatMessage message) {
        BaseUser baseUser = (BaseUser) authentication.getPrincipal();
        System.out.println("message = " + message);
        message.setNickName(baseUser.getNickName());
        message.setFrom(baseUser.getUsername());
        message.setDate(new Date());
        // 前端监听这个队列中的消息内容
        simpMessagingTemplate.convertAndSendToUser(message.getTo(), "/queue/chat", message);
    }
}
